package com.domain.common;

import org.apache.log4j.*;

import java.io.IOException;

/**
 * 系统日志配置类
 *
 * @author Administrator
 */
public class AppLogger extends Logger {


    private static AppLoggerFactory appLoggerFactory = new AppLoggerFactory();

    public AppLogger(String name) {
        super(name);
    }

    public static Logger getLogger(String name, String logLevel, boolean isStoreFile) {
        //tomcat路径
        String path = System.getProperty("catalina.home");
        path += "/webapps/logs/";
        //将日志放在tomcat路径下
        String fileName = path + name + ".log";

        Logger logger = Logger.getLogger(name, appLoggerFactory);
        DailyRollingFileAppender fileAppender = (DailyRollingFileAppender) logger.getAppender(name);

        PatternLayout layout = new PatternLayout("【AppLog】 %d{yyyy-MM-dd HH:mm:ss} %C %M %L %-5p %m%n");
        Level level = Level.INFO;
        if (logLevel.equalsIgnoreCase("DEBUG")) {
            level = Level.DEBUG;
        } else if (logLevel.equalsIgnoreCase("WARN")) {
            level = Level.WARN;
        } else if (logLevel.equalsIgnoreCase("ERROR")) {
            level = Level.ERROR;
        } else if (logLevel.equalsIgnoreCase("FATAL")) {
            level = Level.FATAL;
        }
        logger.setLevel(level);
        if (isStoreFile) {
            if (fileAppender == null) {
                try {

                    fileAppender = new DailyRollingFileAppender(layout, fileName, "'_'yyyyMMdd'.log'");
                    fileAppender.setName(name);
                } catch (IOException e) {
                    throw new IllegalStateException(e);
                }
            }
            fileAppender.setThreshold(level);
            logger.addAppender(fileAppender);
        } else if (fileAppender != null) {
            logger.removeAppender(name);
            fileAppender.close();
        }
        ConsoleAppender consoleAppender = null;
        Category c = logger;
        while (c != null) {
            consoleAppender = (ConsoleAppender) c.getAppender("console");
            if (consoleAppender != null) {
                break;
            }
            c = c.getParent();
        }
        if (consoleAppender == null) {
            consoleAppender = new ConsoleAppender(layout);
            consoleAppender.setThreshold(level);
            consoleAppender.setName("console");
            logger.addAppender(consoleAppender);
        }
        return logger;
    }


}
